import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:magic_car/baoxiu/guarantee.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/jiance/pre_test_report.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/user/userPrivate.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:magic_car/main.dart';
import 'package:package_info/package_info.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';

class GurateencarPage extends StatefulWidget {
  GurateencarPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<GurateencarPage> {
  List messagelist = [];
  int page = 1;
  List carlist = [];
  String keyword = "";
  ScrollController _controller = new ScrollController();
  initState() {
    super.initState();

    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        loadData();
      }
    });

    loadData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        backgroundColor: Colours.base_page_color,
        appBar: AppBar(
          titleSpacing: 0,
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            "保修车源",
            style: TextStyle(fontSize: Config.title_size),
          ),
        ),
        body:
            // ListView.builder(
            //   itemCount: messagelist.length,
            //   itemBuilder: (BuildContext context,int index){
            //   return messageitem(messagelist[index]);
            // }),
            new Center(
                child: Container(
                    decoration: new BoxDecoration(
                      color: Colours.base_page_color,
                    ),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.topLeft,
                          child: SizedBox(
                              width: double.infinity,
                              height: 50,
                              child: Padding(
                                  padding:
                                      new EdgeInsets.fromLTRB(15, 5, 15, 0),
                                  // padding: new EdgeInsets.all(10),
                                  child: Container(
                                      child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          children: <Widget>[
                                        Expanded(
                                          child: new Container(
                                            child: new TextField(
                                              onSubmitted: (value) {
                                                print(value);
                                                //if(value=="")return;
                                                setState(() {
                                                  keyword = value;
                                                  page = 1;
                                                  // end = false;
                                                });
                                                print('搜索');
                                                loadData();
                                              },
                                              // controller: _phonecontroller,
                                              decoration: new InputDecoration(
                                                  border: InputBorder.none,
                                                  hintText: '搜索',
                                                  prefixIcon:
                                                      Icon(Icons.search)),
                                            ),
                                            decoration: new BoxDecoration(
//背景
                                              color: Colors.white,
                                              //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(25.0)),
                                              //设置四周边框
                                              border: new Border.all(
                                                  width: 1,
                                                  color: Colors.white),
                                            ),
                                          ),
                                        ),
                                      ])))),
                        ),
                        Align(
                            alignment: Alignment.bottomCenter,
                            child: Padding(
                                padding: new EdgeInsets.fromLTRB(0, 60, 0, 10),
                                child: new RefreshIndicator(
                                  onRefresh: _onRefresh,
                                  child: ListView.builder(
                                      itemCount: carlist.length,
                                      itemBuilder:
                                          (BuildContext context, int index) {
                                        return messageitem(carlist[index]);
                                      }),
                                ))),
                      ],
                    ))));
  }

  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        page = 1;
      });
      loadData();
    });
  }

  //加载数据
  loadData() async {
    EasyLoading.show(status: '加载中...');
    // if(keyword!=""){
    //   print(keyword);
    // if(end)return;
    // }

    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map['page'] = page.toString();
    map['keyword'] = keyword;
    map["uid"] = pref.getString('uid');
    var role = pref.getString("role");
    map["type"] = role;
    // map["page"] = page.toString();
    // map["keyword"] = keyword;
    print(map);

    HttpHelper.post(HttpHelper.API_Guranteencars, (data) async {
      EasyLoading.dismiss();
      if (data != null) {
        print(data);
        print(data["info"].length.toString());
        if (data["info"].length == 0) {
          Toast.show('暂无更多数据', context);
        } else {
          if (page == 1) carlist.clear();
          carlist.addAll(data['info']);
          setState(() {
            carlist = carlist;
          });
          page++; //增加页面
        }
      }
    }, params: map);
  }

  Widget messageitem(data) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.all(5),
      padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: Row(
        children: [
          SizedBox(
              width: 120,
              height: 100,
              child: (new Container(
                  // height: 50,
                  // width: 50,
                  child:
                      Image.asset('resource/images/baoxiu/zhibaoimg.jpeg')))),
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                      child: Text(
                        '${data['order_info']['brand_string']['name']} ${data['order_info']['cartype_string']['name']}',
                        style: TextStyle(fontSize: 16),
                      )),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                      child: Text("车架：${data['vin']}")),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                      child: Text("商家：${data['bussiness_name']}")),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                      child: Text(
                        "点击下单查看权益和价格",
                        style:
                            TextStyle(color: Colours.bj_red_r1, fontSize: 14),
                      )),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                      child: Text("${data['updated_at']}",
                          style: TextStyle(
                            fontSize: 13,
                            color: Colours.text_gray,
                          ))),
                  Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
                      child: Row(
                        children: [
                          Container(
                            decoration: BoxDecoration(
                              color: Colours.bj_orange_o2,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0)),
                            ),
                            padding: EdgeInsets.fromLTRB(10, 7, 10, 7),
                            // color: Colours.bj_green_g1,
                            child: InkWell(
                              onTap: (){
                                 Navigator.of(context).push(
                                                            new MaterialPageRoute(
                                                                builder: (_) {
                                                          return new GuaranteePage(
                                                               "${data['order_id']}",2);
                                                        }));
                              },
                              child: Center(
                                child: Text(
                                  '立即购买',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                          ),
                          Container(
                            width: 20,
                          ),
                          // Container(
                          //   decoration: BoxDecoration(
                          //     color: Colours.bj_orange_o2,
                          //     borderRadius:
                          //         BorderRadius.all(Radius.circular(5.0)),
                          //   ),
                          //   padding: EdgeInsets.fromLTRB(10, 7, 10, 7),
                          //   //  color: Colours.bj_orange_o2,
                          //   child: InkWell(
                          //     onTap: () {
                          //       print('${data['order_id']}');
                          //       Navigator.of(context)
                          //           .push(new MaterialPageRoute(builder: (_) {
                          //         return new PapularinspectReults(
                          //             '${data['order_id']}', 1);
                          //       }));
                          //     },
                          //     child: Center(
                          //       child: Text(
                          //         '查看结果',
                          //         style: TextStyle(color: Colors.white),
                          //       ),
                          //     ),
                          //   ),
                          // )
                        ],
                      ))
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
